package com.beiye.drivertransport.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.NewPrejobCourseDetailsActivity;
import com.beiye.drivertransport.SubActivity.NewSpecifiedAndCourseDetailsActivity;
import com.beiye.drivertransport.SubActivity.SignActivity;
import com.beiye.drivertransport.SubActivity.SignCourseActivity;
import com.beiye.drivertransport.adapter.MyGridViewAdapter;
import com.beiye.drivertransport.adapter.PopWindowApt;
import com.beiye.drivertransport.bean.LearnRecordBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.CustomProgressDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.beiye.drivertransport.view.ShowGridView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by Lc on 2017/11/23.
 */
//学习记录（这个界面暂时不用）
public class LearnRecordsFgt extends TwoBaseFgt {


    ExpandableListView record_lv;

    TextView tv_record;

    TextView img_down;//down

    View empty_view;
    private MyExpandableListViewAdapter adapter;
    private PopWindowApt popWindowApt;
    private PopupWindow mPopWindow;
    private CustomProgressDialog dialog;

    @Override
    public int getLayoutId() {
        return R.layout.main_learn_records_fgt;
    }

    public void onClick(View view) {


    }

    @Override
    public void initData() {
        record_lv = (ExpandableListView) getActivity().findViewById(R.id.record_expandablelistview);
        tv_record = (TextView) getActivity().findViewById(R.id.tv_record);
        img_down = (TextView) getActivity().findViewById(R.id.img_record);
        empty_view = (View) getActivity().findViewById(R.id.empty_view);

        tv_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popWindowApt == null || popWindowApt.getCount() == 1) {
                    return;
                } else {
                    showPopupWindow();
                }
            }
        });

        //选中公司方法
        initCompany();

        initUi();
    }

    private void initUi() {
        record_lv.setGroupIndicator(null);//去掉箭头
        record_lv.setEmptyView(empty_view);
        record_lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {


                return true;
            }
        });
    }

    private void initCompany() {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        List<LoginUserBean.DataBean.CurUserOrgBean> curuserOrglist = data.getCur_userOrg();
        if (curuserOrglist.size() == 0) {
            img_down.setVisibility(View.INVISIBLE);
            return;
        }
        String orgName = curuserOrglist.get(0).getOrgName();
        String orgId = curuserOrglist.get(0).getOrgId();
        int minPer = curuserOrglist.get(0).getMinPer();
        tv_record.setText(orgName);
        //orgId
        SharedPreferences sp = getActivity().getSharedPreferences("orgId100",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("orgId", orgId);
        editor.putInt("minPer", minPer);
        editor.commit();
        requestData();
        popWindowApt = new PopWindowApt(getActivity(), curuserOrglist, R.layout.popwindow_item_layout);
        if (popWindowApt.getCount() == 1) {
            img_down.setVisibility(View.INVISIBLE);
        } else {
            img_down.setVisibility(View.VISIBLE);
        }
    }

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_layout, null);
        mPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        ListView lv_company = (ListView) contentView.findViewById(R.id.lv_company);
        lv_company.setAdapter(popWindowApt);
        mPopWindow.showAtLocation(tv_record, Gravity.CENTER, 0, 0);
//        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
//        mPopWindow.showAsDropDown(tv_record);
        lv_company.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (popWindowApt != null) {

                    String orgName = popWindowApt.getItem(position).getOrgName();
                    String orgId = popWindowApt.getItem(position).getOrgId();
                    int minPer = popWindowApt.getItem(position).getMinPer();
                    mPopWindow.dismiss();
                    tv_record.setText(orgName);
                    //orgId
                    SharedPreferences sp = getActivity().getSharedPreferences("orgId100",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("orgId", orgId);
                    editor.putInt("minPer", minPer);
                    editor.commit();
                    requestData();

                }
            }
        });
    }

    //    public void initUiData(String orgId) {
//        LoginUserBean userInfo = UserManger.getUserInfo();
//        String userId = userInfo.getUserId();
//
//
//        new Login().getrRecordLearning(userId,this,1);
//
//    }
    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            Map<LearnRecordBean.RowsBean, List<LearnRecordBean.RowsBean.ListCourseBean>> dataset = new HashMap<>();
            LearnRecordBean learnRecordBean = JSON.parseObject(result, LearnRecordBean.class);
            List<LearnRecordBean.RowsBean> rows = learnRecordBean.getRows();
            for (int i = 0; i < rows.size(); i++) {
                List<LearnRecordBean.RowsBean.ListCourseBean> listCourse = rows.get(i).getListCourse();
                dataset.put(rows.get(i), listCourse);
            }
            adapter = new MyExpandableListViewAdapter(getActivity(), rows, dataset);
            record_lv.setAdapter(adapter);
            //    dialog.dismiss();
        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    public void requestData() {

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        SharedPreferences sp = getActivity().getSharedPreferences("orgId100",
                Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        //   dialog = CustomProgressDialog.show(getActivity(), "", true, null);
        showLoadingDialog("加载 . . .");
        new Login().getrRecordLearning(userId, orgId, this, 1);
    }


    @Override
    public void onUserVisible() {
        //   requestData();//有新数据从新刷新一遍
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        SharedPreferences sp = getActivity().getSharedPreferences("orgId100",
                Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        //   showLoadingDialog("加载 . . .");
        new Login().getrRecordLearning(userId, orgId, this, 1);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    private class MyExpandableListViewAdapter extends BaseExpandableListAdapter {
        private Context context;
        private List<LearnRecordBean.RowsBean> rows;
        private Map<LearnRecordBean.RowsBean, List<LearnRecordBean.RowsBean.ListCourseBean>> dataset;

        public MyExpandableListViewAdapter(Context context, List<LearnRecordBean.RowsBean> rows, Map<LearnRecordBean.RowsBean, List<LearnRecordBean.RowsBean.ListCourseBean>> dataset) {
            this.context = context;
            this.rows = rows;
            this.dataset = dataset;
        }

        //  获得某个父项的某个子项
        @Override
        public Object getChild(int parentPos, int childPos) {
            return dataset.get(rows.get(parentPos)).get(childPos);
        }

        //  获得父项的数量
        @Override
        public int getGroupCount() {
            return dataset.size();
        }

        //  获得某个父项的子项数目
        @Override
        public int getChildrenCount(int parentPos) {
            return dataset.get(rows.get(parentPos)).size();
        }

        //  获得某个父项
        @Override
        public Object getGroup(int parentPos) {
            return dataset.get(rows.get(parentPos));
        }

        //  获得某个父项的id
        @Override
        public long getGroupId(int parentPos) {
            return parentPos;
        }

        //  获得某个父项的某个子项的id
        @Override
        public long getChildId(int parentPos, int childPos) {
            return childPos;
        }

        //  按函数的名字来理解应该是是否具有稳定的id，这个方法目前一直都是返回false，没有去改动过
        @Override
        public boolean hasStableIds() {
            return false;
        }

        //  获得父项显示的view
        @Override
        public View getGroupView(int parentPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.record_parent_item, null);
            }
            view.setTag(R.layout.record_parent_item, parentPos);
            view.setTag(R.layout.record_child_item, -1);
            ImageView img_parent = (ImageView) view.findViewById(R.id.img_parent);
            TextView tv_chName = (TextView) view.findViewById(R.id.tv_parent);//学时名称
            TextView tv_creationDate = (TextView) view.findViewById(R.id.tv_parent3);//开始日期
            TextView tv_ChLength = (TextView) view.findViewById(R.id.tv_parent6);//设定实际时长与时长
            TextView tv_timesum = (TextView) view.findViewById(R.id.tv_parent2);//学时
            ImageView tv_comple = (ImageView) view.findViewById(R.id.tv_parent4);//完成
            ImageView tv_complesign = (ImageView) view.findViewById(R.id.tv_parent8);//完成签名
            ImageView tv_Notthrough = (ImageView) view.findViewById(R.id.tv_parent5);//未通过
            TextView record_parent_line = (TextView) view.findViewById(R.id.record_parent_line);
            TextView record_parent_sign = (TextView) view.findViewById(R.id.tv_parent9);//签名按钮
            RelativeLayout re_des = (RelativeLayout) view.findViewById(R.id.re_des);
            TextView tv_des = (TextView) view.findViewById(R.id.tv_des);//审核描述
            ShowGridView gv_parent = (ShowGridView) view.findViewById(R.id.gv_parent);
            ImageView tv_checktgrough = (ImageView) view.findViewById(R.id.tv_parent7);//抽查通过
            LinearLayout re_nodata = (LinearLayout) view.findViewById(R.id.re_nodata);//子类无数据
            gv_parent.setClickable(false);
            gv_parent.setPressed(false);
            gv_parent.setEnabled(false);
            //        LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) record_parent_line.getLayoutParams(); //取控件textView当前的布局参数

            final LearnRecordBean.RowsBean rowsBean = rows.get(parentPos);

            if (rowsBean.getPjtMark() == 1) {
                tv_chName.setText("岗前培训 · " + rowsBean.getChName());
            } else {

                tv_chName.setText(rowsBean.getChName());
            }


            long creationDate = rowsBean.getCreationDate();
            //mill为你龙类型的时间戳
            Date date = new Date(creationDate);
            String begin = "";
            try {
                //yyyy表示年MM表示月dd表示日
                //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                //进行格式化
                begin = sdf.format(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            tv_creationDate.setText("开始时间: " + begin);


            tv_timesum.setText(rowsBean.getChNo() + "学时");
            tv_ChLength.setText(rowsBean.getActualChLength() + "分钟/" + rowsBean.getSetChLength() + "分钟");
            if (rowsBean.getCheckMark() == 2) {

                tv_Notthrough.setImageResource(R.mipmap.bj_21);


            } else if (rowsBean.getCheckMark() == 1) {
                tv_Notthrough.setImageResource(R.mipmap.bj_09);


            } else if (rowsBean.getCheckMark() == 0) {
                tv_Notthrough.setImageResource(R.mipmap.bj_03);

            }

            if (rowsBean.getFinishMark() == 1) {
                tv_comple.setImageResource(R.mipmap.bj_11);
//                if(rowsBean.getPjtMark()==1)//判断是否是岗前培训
//                {
//                    tv_complesign.setVisibility(View.GONE);
//                    record_parent_sign.setVisibility(View.GONE);//签名按钮
//
//                }else{
                tv_Notthrough.setVisibility(View.VISIBLE);
                tv_complesign.setVisibility(View.VISIBLE);
                tv_complesign.setImageResource(R.mipmap.bj_112);//未签名
                record_parent_sign.setVisibility(View.VISIBLE);//签名按钮
                record_parent_sign.setText("签名");
                record_parent_sign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isFastDoubleClick()) {
                            return;
                        }
                        int sn = rowsBean.getSn();
                        Bundle bundle = new Bundle();
                        bundle.putInt("sn", sn);
                        startActivity(SignActivity.class, bundle);
                    }
                });
                //         }

            } else if (rowsBean.getFinishMark() == 2) {
                tv_comple.setImageResource(R.mipmap.bj_11);
//                if(rowsBean.getPjtMark()==1)//判断是否是岗前培训
//                {
//                    tv_complesign.setVisibility(View.GONE);
//                    record_parent_sign.setVisibility(View.GONE);//签名按钮
//                }else {
                tv_Notthrough.setVisibility(View.VISIBLE);
                tv_complesign.setVisibility(View.VISIBLE);
                tv_complesign.setImageResource(R.mipmap.bj_111);//已签名
                record_parent_sign.setVisibility(View.VISIBLE);//签名按钮
                record_parent_sign.setText("查看签名");
                record_parent_sign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isFastDoubleClick()) {
                            return;
                        }
                        int sn = rowsBean.getSn();
                        Bundle bundle = new Bundle();
                        bundle.putInt("sn", sn);
                        startActivity(SignActivity.class, bundle);
                    }
                });
                //         }
            } else if (rowsBean.getFinishMark() == 0) {
                tv_comple.setImageResource(R.mipmap.bj_23);
//                if(rowsBean.getPjtMark()==1)//判断是否是岗前培训
//                {
//                    tv_complesign.setVisibility(View.GONE);
//                    record_parent_sign.setVisibility(View.GONE);//签名按钮
//                }else {
                tv_Notthrough.setVisibility(View.GONE);
                tv_complesign.setVisibility(View.GONE);
                record_parent_sign.setVisibility(View.GONE);
                //              }
            }

            if (rowsBean.getSpotCheckMark() == 1) {
                tv_checktgrough.setImageResource(R.mipmap.bj_07);
            } else if (rowsBean.getSpotCheckMark() == 2) {
                tv_checktgrough.setImageResource(R.mipmap.bj_19);
            } else {
                tv_checktgrough.setVisibility(View.INVISIBLE);
            }

            if (b)//判断展开
            {

                if (rowsBean.getListCourse().size() == 0) {
                    re_nodata.setVisibility(View.VISIBLE);
                }
                gv_parent.setVisibility(View.VISIBLE);
                List<LearnRecordBean.RowsBean.PhotoListBean> photoList = rows.get(parentPos).getPhotoList();
                MyGridViewAdapter gridViewAdapter = new MyGridViewAdapter(getActivity(), photoList);
                gv_parent.setAdapter(gridViewAdapter);
//                tv_comple.setVisibility(View.VISIBLE);
//                tv_checktgrough.setVisibility(View.VISIBLE);
//                tv_Notthrough.setVisibility(View.VISIBLE);
                img_parent.setImageResource(R.mipmap.jianhao);
//                linearParams.height = 5;// 控件的高强制设成3
//                record_parent_line.setLayoutParams(linearParams);
                record_parent_line.setVisibility(View.GONE);
                if (rowsBean.getCheckMark() == 2) {
                    //   tv_Notthrough.setImageResource(R.mipmap.bj_21);
                    re_des.setVisibility(View.VISIBLE);
                    tv_des.setText(rows.get(parentPos).getCheckDesc());

                } else if (rowsBean.getCheckMark() == 1) {

                    //     tv_Notthrough.setImageResource(R.mipmap.bj_09);
                    re_des.setVisibility(View.GONE);
                } else if (rowsBean.getCheckMark() == 0) {

                    //   tv_Notthrough.setImageResource(R.mipmap.bj_03);
                    re_des.setVisibility(View.GONE);
                }

            } else {

                re_nodata.setVisibility(View.GONE);
                gv_parent.setVisibility(View.GONE);
                re_des.setVisibility(View.GONE);
//                tv_comple.setVisibility(View.INVISIBLE);
//                tv_Notthrough.setVisibility(View.INVISIBLE);
//                tv_checktgrough.setVisibility(View.INVISIBLE);
                img_parent.setImageResource(R.mipmap.jiahao);
//                linearParams.height = 16;// 控件的高强制设成15
//                record_parent_line.setLayoutParams(linearParams);
                record_parent_line.setVisibility(View.VISIBLE);
            }

            return view;
        }

        //  获得子项显示的view
        @Override
        public View getChildView(int parentPos, int childPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.record_child_item, null);
            }
            view.setTag(R.layout.record_parent_item, parentPos);
            view.setTag(R.layout.record_child_item, childPos);
            TextView tv_courseName = (TextView) view.findViewById(R.id.tv_child);
            TextView tv_creationDate = (TextView) view.findViewById(R.id.tv_child1);
            TextView tv_newlearning = (TextView) view.findViewById(R.id.tv_child5);//从新学习
            ImageView tv_muMark = (ImageView) view.findViewById(R.id.tv_child2);


            final LearnRecordBean.RowsBean rowsBean = rows.get(parentPos);
            final LearnRecordBean.RowsBean.ListCourseBean listCourseBean = dataset.get(rowsBean).get(childPos);
            tv_courseName.setText(listCourseBean.getCourseName());
            long creationDate = listCourseBean.getCreationDate();
            //mill为你龙类型的时间戳
            Date date = new Date(creationDate);
            String learn = "";
            try {
                //yyyy表示年MM表示月dd表示日
                //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                //进行格式化
                learn = sdf.format(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            tv_creationDate.setText(learn);
            if (listCourseBean.getMuMark() == 1) {
                tv_muMark.setVisibility(View.VISIBLE);
            } else {
                tv_muMark.setVisibility(View.INVISIBLE);
            }

            if (rowsBean.getCheckMark() == 0)//待审核
            {
                tv_newlearning.setVisibility(View.VISIBLE);
                tv_newlearning.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (rowsBean.getPjtMark() == 1)//从新学习跳转岗前培训课程
                        {
                            showLoadingDialog("正在加载");
                            int utchSn = rowsBean.getSn();
                            int sn1 = listCourseBean.getSn();
                            int tcSn = listCourseBean.getTcSn();
                            SharedPreferences sp = getActivity().getSharedPreferences("orgId100",
                                    Context.MODE_PRIVATE);
                            int minPer = sp.getInt("minPer", 0);
                            Bundle bundle = new Bundle();
                            bundle.putInt("utchSn", utchSn);
                            bundle.putInt("sn", sn1);
                            bundle.putInt("tcSn", tcSn);
                            bundle.putInt("minPer", minPer);
                            startActivity(NewPrejobCourseDetailsActivity.class, bundle);

                        } else {//课程超市和指定学习从新学习
                            showLoadingDialog("正在加载");
                            int utchSn = rowsBean.getSn();
                            int sn2 = listCourseBean.getSn();
                            int tcSn = listCourseBean.getTcSn();
                            SharedPreferences sp = getActivity().getSharedPreferences("orgId100",
                                    Context.MODE_PRIVATE);
                            int minPer = sp.getInt("minPer", 0);
                            Bundle bundle = new Bundle();
                            bundle.putInt("utchSn", utchSn);
                            bundle.putInt("sn", sn2);
                            bundle.putInt("tcSn", tcSn);
                            bundle.putInt("minPer", minPer);
                            startActivity(NewSpecifiedAndCourseDetailsActivity.class, bundle);
                        }
                    }
                });

            } else {
                tv_newlearning.setVisibility(View.GONE);
            }


            return view;
        }

        //  子项是否可选中，如果需要设置子项的点击事件，需要返回true
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }
}
